<template>
	<view class="app-splash e-flex-xy-center">
		<view v-if="splashOption.open && isOpen ">
			<view class="app-splash__jump c-white e-font-24" v-show="timeoutShow" @tap="end">{{ $t('common.跳过') }}{{ time }}</view>
			<swiper class="app-splash__swiper" @change="handleChange">
				<block v-for="(item, index) in splashOption.imgList" :key="index">
					<swiper-item :item-id="`${index}`" >
						<image mode="aspectFit" class="app-splash__img-item" :key="index" :src="$fullLink(item.url)" @tap="$layoutGoTo(item.link)"></image>
					</swiper-item>
				</block>
			</swiper>
		</view>
		<view class="app-splash__loading e-rela" v-else>
			<view class="app-splash__loading__mask"></view>
			<view class="app-splash__loading__content e-rela bg-white">
				<image :src="`/static/${tenant}.png`" ></image>
			</view>
		</view>

	</view>
</template>

<script lang="ts" setup>
	import {
		ref
	} from 'vue'
	import {
		baseInitDispatcher
	} from '@/common/init'
	import {
		useCurrentInstance,
		useLogin
	} from '@/common/hooks'
	import {
		onLoad
	} from '@dcloudio/uni-app'
	import {
		useInit,
		useBasics
	} from '@/common/stores';
	import {
		storeToRefs
	} from 'pinia'
	import {
		sceneParamsToObj,
		deepClone
	} from '@/common/utils'
	import {postSupperAppLogin} from '@/common/request/api'

	const props = defineProps({
		url: String,
		scene: String,
		salt: String,
		token:String
	})

	const ctx = useCurrentInstance()
	const {getBasicsSetting} = useBasics()
	const { login } = useLogin();
	
	props.token&&login(props.token)

	const initStore = useInit()
	
	const tenant = uni.getStorageSync('tenant');

	const {
		splashOption
	} = storeToRefs(initStore)

	const isOpen = ref(false)
	const logo = ref('')
	
	// #ifdef MP-WEIXIN
	let extConfig = wx.getExtConfigSync() ? wx.getExtConfigSync() : null
	if (extConfig !== null) {
		logo.value = extConfig.head_img
	}
	// #endif


	let pageQuery:Record<string,string> = {}
	
	const handleChange = (e:{detail:{current:number}}) => {
		if (splashOption.value.openType === 2 && e.detail.current === splashOption.value.imgList.length - 1) {
			timeout(3)
		}
	}

	const init = () => {
		if (splashOption.value.open) {
			let splashSetting = uni.getStorageSync('splashSetting') as (typeof initStore['splashOption'] & {displayedNumber:number})
			let splashImgList = splashSetting?.imgList
			let {
				openType,
				timing,
				showType,
				showCount,
				imgList
			} = splashOption.value
			if (showType === 1) {
				// 上次配置与本次配置不同，显示广告图
				if (splashSetting.openType !== openType) {
					isOpen.value = true
					// 定时关闭
					if (openType === 1) {
						timeout(timing)
					}
				} else {
					// 配置相同的情况下判断图片是否相同
					// 定时关闭
					if (openType === 1) {
						// 图片不相同，则显示广告
						if (splashImgList[0].url !== imgList[0].url) {
							isOpen.value = true
							timeout(timing)
						} else {
							end()
						}
					} else {
						// 图片长度不一致或列表内图片不完全一致，则展示广告
						let num = 0
						// 图片列表长度一致，对比列表内的图片是否相同
						if (splashImgList.length === imgList.length) {
							splashImgList.forEach((item, index) => {
								if (item.url === imgList[index].url) {
									num++
								}
							})
							// 图片一致，跳过广告
							if (num === splashImgList.length) {
								end()
							} else {
								isOpen.value = true
							}
						}
					}
				}
				uni.setStorageSync('splashSetting', splashOption.value)

			} else {
				
				// 多次展示广告
				// 没有缓存次数或已显示的次数少于设置的次数
				if (!splashSetting.displayedNumber || splashSetting.displayedNumber < showCount) {
					isOpen.value = true
					if (openType === 1) {
						timeout(timing)
					}
					uni.setStorageSync('splashSetting', {
						...splashOption.value,
						displayedNumber: splashSetting.displayedNumber ? splashSetting.displayedNumber + 1 : 1
					})
				} else {
					end()
				}
			}
		} else {
			end()
		}

	}
	const time = ref(0)
	const timeoutShow = ref(false)
	let interval: number;

	const timeout = (timing: number) => {
		time.value = timing
		timeoutShow.value = true
		interval = setInterval(() => {
			time.value--
			if (!time.value) {
				end()
			}
		}, 1000)
	}
	
	let hasLogin = false

	const end = () => {
		
		clearInterval(interval)
		// #ifdef H5
		let params = deepClone({ ...pageQuery })
		delete params.url
		if (props.url && props.url !== '/pages/tabbar/index') {
			try{
				ctx.$goReLaunch(props.url, params)
			}catch(err) {
				console.log(err,'err')
			}
			
		} else {
			ctx.$switchTab('/pages/tabbar/index', params)
		}
		// #endif
		// #ifndef H5 
		ctx.$switchTab('/pages/tabbar/index')
		// #endif
		
	}
	
	const appLogin = () => {
		return new Promise((resolve,reject) => {
			// #ifdef APP
			if (import.meta.env.DEV){
				resolve()
				return
			}
			uni.sendNativeEvent(
				'autoLogin',
				{
					msg: 'sendAutoLogin'
				},
				(ret) => {
					let params = {
						code: ret,
						salt: uni.getStorageSync('userSalt')
					};
					postSupperAppLogin(params)
						.then(async (res) => {
							uni.removeStorageSync('userSalt');
							await login(res.data.access_token);
							resolve()
							
						})
						.catch((err) => {
							reject(err);
						})
				}
			);
			return ;
			// #endif
			resolve()
		})
	}

	//等待项目基础的配置数据的请求完后才能进入首页
	baseInitDispatcher.on(async () => {
		 await getBasicsSetting();
		appLogin().finally(() => {
			init()
		})
		
	})

	onLoad(() => {
		logo.value = uni.getStorageSync('logo')
		if (props.scene) {
			let query = sceneParamsToObj(props.scene)
			pageQuery = query
			if (query.salt) {
				uni.setStorageSync('userSalt', query.salt)
			}
		} else {
			Object.keys(props).forEach(key => {
				if(props[key]){
					pageQuery[key] = props[key]
				}
			})
			if (props.salt) {
				uni.setStorageSync('userSalt', props.salt)
			}
		}

	})
</script>

<style lang="scss" scoped>
	@include appBem_b(splash) {
		height: 100vh;
		
		@include appBem_e(swiper){
			width: 100vw;
			height: 100vh;
		}
		@include appBem_e(img-item) {
			width: 100vw;
			height: 100vh;
		}
		@include appBem_e(jump) {
			position: fixed;
			/* #ifdef H5 */
			top: 40rpx;
			/* #endif */
			/* #ifndef H5 */
			top: 176rpx;
			/* #endif */
			right: 20rpx;
			width: 120rpx;
			height: 64rpx;
			background: rgba(0, 0, 0, 0.34);
			border-radius: 32rpx;
			z-index: $z-index-high;
			line-height: 64rpx;
			text-align: center;
		}

		@include appBem_e(loading) {
			width: 188rpx;
			height: 188rpx;
			padding: 8rpx;
			overflow: hidden;
			border-radius: 50%;



			&__mask {
				width: 100%;
				height: 100%;
				position: absolute;
				top: 0;
				left: 0;
				z-index: 2;
				animation: spin 2s linear infinite;
				border-radius: 50%;

				// &::before {
				// 	content: '';
				// 	display: block;
				// 	position: absolute;
				// 	bottom: 0;
				// 	left: calc(50% - 5px);
				// 	width: 8rpx;
				// 	height: 8rpx;
				// 	border-radius: 50%;
				// 	background-color: #fff;
					
				// }

				&::after {
					content: '';
					display: block;
					position: absolute;
					bottom: 0;
					left: 50%;
					width: 50%;
					height: 60%;
					background-image: linear-gradient(90deg, #b6b6b6 0%, #fff 100%);
					
				}
			}

			@keyframes spin {
				0% {
					transform: rotate(0deg);
				}

				100% {
					transform: rotate(360deg);
				}
			}

			&__content {
				width: 100%;
				height: 100%;
				z-index: 10;
				border-radius: 50%;
			}

			image {
				width: 160rpx;
				height: 160rpx;
				border-radius: 50%;
			}
		}
	}
</style>
